package simpleGui;

import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;

import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PGraphics;

public class GuiCheckButton extends GuiComponent implements ItemSelectable {
	boolean over;
	public boolean state;
	Vector<ItemListener> itemListener = new Vector<ItemListener>();

	public GuiCheckButton(Gui gui, int x, int y, int w, int h, boolean state) {
		this.gui = gui;
		this.setDimensions(x, y, w, h);
		this.state = state;
		gui.parent.addMouseListener(this);
		displayLabel = true;
	}

	public GuiCheckButton(Gui gui, int x, int y, int w, int h, boolean state,
			String label) {
		this(gui, x, y, w, h, state);
		this.label = label;
		displayLabel = true;
	}

	public void setValue(int mx, int my) {
		if (contains(mx, my)) {
			flipState();
		}
	}

	public void flipState() {
		state = !state;
		int eventType = ItemEvent.DESELECTED;
		if (state)
			eventType = ItemEvent.SELECTED;
		ItemEvent event = new ItemEvent(this, 0, this, eventType);
		for (int i = 0; i < itemListener.size(); i++) {
			itemListener.get(i).itemStateChanged(event);
		}
	}

	public void display(PGraphics g) {
		g.pushStyle();
		if (state) {
			g.fill(gui.getFillColorActivated());
		} else {
			g.fill(gui.getFillColor());
		}
		g.strokeWeight(gui.getStrokeWeight());
		g.stroke(gui.getStrokeColor());
		g.rect(x, y, w, h);
		g.fill(gui.getTextColor());
		if (label != null && this.displayLabel) {
			g.text(label, x + gui.getPadding(), y + h - gui.getPadding());
		}
		g.popStyle();
		displayChildren(g);
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		setValue(arg0.getX(), arg0.getY());
	}

	@Override
	public void addItemListener(ItemListener arg0) {
		// TODO Auto-generated method stub
		itemListener.add(arg0);
	}

	@Override
	public Object[] getSelectedObjects() {
		// TODO Auto-generated method stub
		if (state)
			return new Object[] { this };
		return null;
	}

	@Override
	public void removeItemListener(ItemListener arg0) {
		// TODO Auto-generated method stub
		itemListener.remove(arg0);
	}

}
